import { useEffect, useState } from "react";
import { Breadcrumb, Table, Input, Select, Button, message, Modal, Tag, Space, Form } from "antd";
import Navigate from "../components/Navigate";
import "./AdminTorrent.css";
import { fetchTorrentDetail, searchTorrents, fetchPendingTorrents,reviewTorrent,listReviewTorrents,removeTorrent } from '../api/AdminTorrentApi';
import {fetchUserInfoByIdService} from '../api/UserApi';
import SeedDetail from "./SeedDetail"; // 导入种子详情组件
const { Option } = Select;
// Define a mapping for category IDs to names
const categoryMapping = {
  401: '电影',
  402: '剧集',
  403: '综艺',
  404: '纪录片',
  405: '动漫',
  406: 'MV',
  407: '体育',
  408: '软件',
  409: '其他',
  410: '游戏',
  411: '学习',
  414: '音乐',
  423: '原创',
};
function AdminTorrent() {
  const [activeView, setActiveView] = useState('all'); // 'all' 或 'pending'
  const [torrents, setTorrents] = useState([]);
  const [pendingTorrents, setPendingTorrents] = useState([]); // State for pending torrents
  const [loading, setLoading] = useState(true); 
  const [userInfo, setUserInfo] = useState(null);
  const [isUserInfoModalVisible, setIsUserInfoModalVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({
    current: 1,
    size: 10, // Default page size
    title: "",
    categoryId: "", // 改为使用categoryId而不是category名称
    status: "",
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedTorrent, setSelectedTorrent] = useState(null);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedSeedId, setSelectedSeedId] = useState(null);
  const [total, setTotal] = useState(0);
const [totalPage, setTotalPage] = useState(0);
const [pageNumbers, setPageNumbers] = useState([]);
  const fetchUserInfo = async (userId) => {
    try {
      const response = await fetchUserInfoByIdService(userId);
      if (response.success) {
        setUserInfo(response.data);
        setIsUserInfoModalVisible(true);
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('获取用户信息失败');
    }
  };
   // 加载种子数据
   const loadTorrents = async () => {
    setLoading(true);
    try {
      let response;
      response = await listReviewTorrents(searchParams.current, searchParams.size);
      
      
      if (response.success) {
        setTorrents(response.data.rows); // Set torrents directly from response.data
        setTorrents(response.data.rows);
        setTotal(response.data.records);
        setTotalPage(Math.ceil(response.data.records / searchParams.size));
        setPageNumbers(getPageNumbers(searchParams.current, Math.ceil(response.data.records / searchParams.size)));
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('加载失败');
    } finally {
      setLoading(false);
    }
  };
  // 加载待审核种子数据
  const loadPendingTorrents = async () => {
    setLoading(true);
    try {
      const response = await fetchPendingTorrents(searchParams.current, searchParams.size);
      if (response.success) {
        setPendingTorrents(response.data.rows);
        setTotal(response.data.records);
        setTotalPage(Math.ceil(response.data.records / searchParams.size));
        setPageNumbers(getPageNumbers(searchParams.current, Math.ceil(response.data.records / searchParams.size)));
            } else {
        message.error(response.msg);
      }} catch (error) {
        message.error('加载待审核种子列表失败');
      } finally {
        setLoading(false);
      }
  };
  // 添加分页控制函数
const handlePageChange = (page) => {
  setSearchParams(prev => ({
    ...prev,
    current: page
  }));
};

const handleSizeChange = (size) => {
  setSearchParams(prev => ({
    ...prev,
    current: 1,
    size: size
  }));
  };
  const getPageNumbers = (current, totalPages, delta = 2) => {
    const pages = [];
    const start = Math.max(1, current - delta);
    const end = Math.min(totalPages, current + delta);
  
    for (let i = start; i <= end; i++) {
      pages.push(i);
    }
  
    if (start > 1) {
      if (start > 2) pages.unshift("...");
      pages.unshift(1);
    }
  
    if (end < totalPages) {
      if (end < totalPages - 1) pages.push("...");
      pages.push(totalPages);
    }
  
    return pages;
  };
  useEffect(() => {
    if (activeView === 'pending') {
      loadPendingTorrents();
    } else {
      loadTorrents();
    }
  }, [activeView, searchParams]);
// 种子点击处理函数
  const handleSeedClick = (id) => {
  setSelectedSeedId(id);
  setIsDetailModalVisible(true);
  };
  const handleDetailModalClose = () => {
    setIsDetailModalVisible(false);
    setSelectedSeedId(null);
  };
  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 20,
    },
    {
      title: '标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 100, 
      render: (title,record) => (
        <Button type="link" onClick={() => handleSeedClick(record.id)}>
          {title}
        </Button>
      )
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      width: 60,
      render: (categoryId) => (
        <Tag color="#ff6699">{categoryMapping[categoryId] || '未知'}</Tag>
      )
    },{
      title: '标签',
      dataIndex: 'tags',
      width: 80,
      render: (tags) => (
        <Tag color="#ff6699">{tags || '无'}</Tag>
      )
    },
    {
      title: '上传者',
      dataIndex: 'userId',
      width: 120,
      render: (userId) => (
        <Button type="link" onClick={() => fetchUserInfo(userId)}>
          {userId}
        </Button>
        
      )
    },
    {
      title: '状态',
      dataIndex: 'underReview', // Use underReview for status
      width: 100,
      render: (underReview) => {
        const statusMap = {
          true: { text: '已审核', color: '#faad14' },
          false: { text: '待审核', color: '#52c41a' },
        };
        const { text, color } = statusMap[underReview] ; // Default to removed
        return <Tag color={color}>{text}</Tag>;
      }
    }, {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        activeView === 'pending' ?
        <Space>
            <Button type="link" onClick={() => handleViewDetails(record.id)}>查看详情</Button>
            <Button type="link" danger onClick={() => handleReview(record.infoHash, 1)}>通过种子</Button>
            <Button type="link" danger onClick={() => handleRemoveTorrent(record.id)}>下架种子</Button>
          </Space>
          :
          <Space>
            <Button type="link" onClick={() => handleViewDetails(record.id)}>查看详情</Button>
            <Button type="link" danger onClick={() => handleRemoveTorrent(record.id)}>下架种子</Button>
          </Space>
      ),
    },
  ];
   // 处理审核
   const handleReview = async (infoHash, isApproved) => {
    try {
      setLoading(true);
      const response = await reviewTorrent(infoHash, isApproved);
      if (response.success) {
        message.success('审核操作成功');
        loadPendingTorrents(); // Reload the pending torrents
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('审核操作失败');
    } finally {
      setLoading(false);
    }
  };
  const handleViewDetails = async (torrentId) => {
    try {
      setLoading(true);
      const response = await fetchTorrentDetail(torrentId); // Call the API to fetch details
      if (response.success) {
        setSelectedTorrent(response.data); // Set the selected torrent details
        setIsModalVisible(true); // Show the modal
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('获取种子详情失败');
    } finally {
      setLoading(false);
    }
  };
// 处理下架种子
const handleRemoveTorrent = async (torrentId) => {
  
        const response = await removeTorrent(torrentId); // Call the API to remove the torrent
  
  };
  return (
    <div className="admin-layout">
      {/* 导航栏 */}
      <Navigate activeItem="种子管理" />
      {/* 主内容区域 */}
      <div className="main-content">
        <div className="torrent-management">
          {/* 头部 */}
          <div className="header">
            <h2>种子管理</h2>
          </div>
          {/* 面包屑导航 */}
          <Breadcrumb 
            className="breadcrumb"
            items={[
              {
                title: '种子管理',
                onClick: () => setActiveView('all'),
                className: activeView === 'all' ? 'active' : ''
              },
              {
                title: '待审核',
                onClick: () => setActiveView('pending'),
                className: activeView === 'pending' ? 'active' : ''
              }
            ]}
          />
    {/* 种子列表 */}
    <Table
            columns={columns}
            dataSource={activeView === 'pending' ? pendingTorrents : torrents}
            rowKey="id"
            loading={loading}
            pagination={false}
          />
          <div className="pagination-container">
  <div className="pagination-info">共 {total} 条数据</div>
  <div className="pagination-controls">
    <button
      onClick={() => handlePageChange(searchParams.current - 1)}
      disabled={searchParams.current === 1}
      className="pagination-btn"
    >
      ‹
    </button>
    {pageNumbers.map((number, index) => (
      <button
        key={index}
        onClick={() => {
          if (typeof number === "number") {
            handlePageChange(number);
          }
        }}
        disabled={number === "..."}
        className={`pagination-btn ${searchParams.current === number ? "active" : ""}`}
      >
        {number}
      </button>
    ))}
    <button
      onClick={() => handlePageChange(searchParams.current + 1)}
      disabled={searchParams.current === totalPage}
      className="pagination-btn"
    >
      ›
    </button>
    <div className="pagination-jump">
      <select
        value={searchParams.size}
        onChange={(e) => {
          handleSizeChange(Number(e.target.value));
        }}
      >
        <option value={10}>10 条/页</option>
        <option value={20}>20 条/页</option>
        <option value={50}>50 条/页</option>
        <option value={100}>100 条/页</option>
      </select>
      <span>跳至</span>
      <input 
        type="number" 
        min={1} 
        max={totalPage} 
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            const page = Number(e.target.value);
            if (page >= 1 && page <= totalPage) {
              handlePageChange(page);
            }
          }
        }} 
        placeholder="页码" 
      />
      <span>页</span>
    </div>
  </div>
</div>

          {/* Modal for Torrent Details */}
          <Modal
            title="种子详情"
            open={isModalVisible}
            onCancel={() => setIsModalVisible(false)}
            footer={[
              activeView === 'pending' ? (
                <>
                  <Button key="reject" danger onClick={() => handleReview(selectedTorrent.infoHash, 0)}>
                    不通过
                  </Button>
                  <Button key="approve" type="primary" onClick={() => handleReview(selectedTorrent.infoHash, 1)}>
                    通过
                  </Button>
                </>
              ) : (
                <>
                  <Button key="remove" danger onClick={() => handleRemoveTorrent(selectedTorrent.id)}>
                    下架种子
                  </Button>
                  <Button key="close" onClick={() => setIsModalVisible(false)}>
                    关闭
                  </Button>
                </>
              )
            ]}
          >
            {selectedTorrent && (
              <div>
                <p><strong>标题:</strong> {selectedTorrent.title}</p>
                <p><strong>分类:</strong> {categoryMapping[selectedTorrent.categoryId] || '未知'}</p>
                <p><strong>标签:</strong> {selectedTorrent.tags}</p>
                <p><strong>上传者:</strong> {selectedTorrent.userId}</p>
                <p><strong>状态:</strong> {selectedTorrent.status}</p>
                <p><strong>下载链接:</strong> <a href={selectedTorrent.downloadLink} target="_blank" rel="noopener noreferrer">下载</a></p>
                {/* Add more fields as necessary */}
              </div>
            )}
          </Modal>
           {/* Modal for User Information */}
        <Modal
          title="用户信息"
          visible={isUserInfoModalVisible}
          onCancel={() => {
            setIsUserInfoModalVisible(false);
            setUserInfo(null); // Clear user info when closing
          }}
          footer={[
            <Button key="close" onClick={() => {
              setIsUserInfoModalVisible(false);
              setUserInfo(null); // Clear user info when closing
            }}>
              关闭
            </Button>
          ]}
        >
          {userInfo && (
            <Form layout="vertical">
              <Form.Item label="ID">
                <Input value={userInfo.id} readOnly />
              </Form.Item>
              <Form.Item label="用户名">
                <Input value={userInfo.username} readOnly />
              </Form.Item>
              <Form.Item label="邮箱">
                <Input value={userInfo.email} readOnly />
              </Form.Item>
              <Form.Item label="权限组">
                <Input value={userInfo.permissionGroupName} readOnly />
              </Form.Item>
              <Form.Item label="状态">
                <Input value={userInfo.status === 0 ? '正常' : '禁用'} readOnly />
              </Form.Item>
              <Form.Item label="创建时间">
                <Input value={new Date(userInfo.createdTime).toLocaleString()} readOnly />
              </Form.Item>
              <Form.Item label="更新时间">
                <Input value={new Date(userInfo.updatedTime).toLocaleString()} readOnly />
              </Form.Item>
              {userInfo.avatarUrl && (
                <Form.Item label="用户头像">
                  <img src={userInfo.avatarUrl} alt="用户头像" style={{ width: '50px', height: '50px' }} />
                </Form.Item>
              )}
            </Form>
          )}
          </Modal>
          {/* 在最后添加种子详情弹窗 */}
          {selectedSeedId && (
            <SeedDetail
              id={selectedSeedId}
              admin={true}
              visible={isDetailModalVisible}
              onClose={handleDetailModalClose}
            />
          )}
        </div>
      </div>
    </div>
    );
}
export default AdminTorrent;